
import Foundation
import CoreTelephony
import SystemConfiguration
import DeviceKit
/// 获取当前时间戳(以秒为单位)
///
/// - Returns: 时间戳
public func getNowTimeTimestamp() ->Int {
    let formatter:DateFormatter = DateFormatter.init()
    formatter.dateStyle = .medium
    formatter.timeStyle = .short
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    formatter.locale =  Locale.init(identifier: "Asia/Beijing")
    let datenow = Date.init()
    let timeSp = datenow.timeIntervalSince1970 * 1000
    return Int(timeSp)
}

/// 获取UUID
///
/// - Returns: UUID
public func getUUID() -> String {
    var uuid:String = ""
    let key = "uuid"
    if XWKeyChainManager.shared.hasPin {
        uuid = XWKeyChainManager.shared.getValue(for: key)!
    }else {
        uuid = UUID().uuidString
        XWKeyChainManager.shared.set(value: uuid, for: key)
    }
    return uuid
}
/// 获取系统设置的第一语言
///
/// - returns：Language
public func getCurrentLanguage() -> String{
    // 返回设备曾使用过的语言列表
    let languages: [String] = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
    // 当前使用的语言排在第一
    let currentLanguage = languages.first
    return currentLanguage ?? "en-CN"
}
///  获取mac地址
///
///  - returns： macAddresss
public func getMacAddress() -> String {
    return UIDevice.current.identifierForVendor!.uuidString
}
/// 获取当前网络状态
///
/// - returns： 网络状态
public func getNetwork() -> String {
    var zeroAddress = sockaddr_storage()
    bzero(&zeroAddress, MemoryLayout<sockaddr_storage>.size)
    zeroAddress.ss_len = __uint8_t(MemoryLayout<sockaddr_storage>.size)
    zeroAddress.ss_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in
            SCNetworkReachabilityCreateWithAddress(nil, address)
        }
    }
    guard let defaultRouteReachability = defaultRouteReachability else {
        return notReachable
    }
    var flags = SCNetworkReachabilityFlags()
    let didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)
    
    guard didRetrieveFlags == true,
          (flags.contains(.reachable) && !flags.contains(.connectionRequired)) == true
    else {
        return notReachable
    }
    if flags.contains(.connectionRequired) {
        return notReachable
    } else if flags.contains(.isWWAN) {
        return cellularType()
    } else {
        return "WiFi"
    }
}
private var notReachable: String {
    get {
        return "notReachable"
    }
}
/// 获取蜂窝数据类型
private  func cellularType() -> String {
        let info = CTTelephonyNetworkInfo()
        var status: String
        
        if #available(iOS 12.0, *) {
            guard let dict = info.serviceCurrentRadioAccessTechnology,
                  let firstKey = dict.keys.first,
                  let statusTemp = dict[firstKey] else {
                return notReachable
            }
            status = statusTemp
        } else {
            guard let statusTemp = info.currentRadioAccessTechnology else {
                return notReachable
            }
            status = statusTemp
        }
        
        if #available(iOS 14.1, *) {
            if status == CTRadioAccessTechnologyNR || status == CTRadioAccessTechnologyNRNSA {
                return "5G"
            }
        }
        
        switch status {
        case CTRadioAccessTechnologyGPRS,
            CTRadioAccessTechnologyEdge,
        CTRadioAccessTechnologyCDMA1x:
            return "2G"
        case CTRadioAccessTechnologyWCDMA,
            CTRadioAccessTechnologyHSDPA,
            CTRadioAccessTechnologyHSUPA,
            CTRadioAccessTechnologyeHRPD,
            CTRadioAccessTechnologyCDMAEVDORev0,
            CTRadioAccessTechnologyCDMAEVDORevA,
        CTRadioAccessTechnologyCDMAEVDORevB:
            return "3G"
        case CTRadioAccessTechnologyLTE:
            return "4G"
        default:
            return notReachable
        }
    }
/// 获取手机型号
///
///  - returns： 手机型号名称
public func getDeviceModel() -> String {
    let deviceModel = Device.identifier
    return deviceModel
}
///  获取手机品牌
///
///   - returns： 手机品牌
public func getDeviceBrand() -> String {
    return UIDevice.current.model
}
///  获取BundleIdentifier
///
///    - returns： BundleIdentifier
public func getBundleIdentifier() -> String {
    let bundleIdentifier = Bundle.main.bundleIdentifier
    return bundleIdentifier!
}
///   获取版本号
///
///    - returns： Version
public func getVersion() -> String {
    let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
    return version
}

public func getAppName() ->String {
    let name = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "Unknown"
    return name
}

///   获取编译版本
///
///    - returns： Build
public func getBuild() -> String {
    let build = Bundle.main.infoDictionary?["CFBundleVersion"]
    return build as! String
}
///   获取屏幕的分辨率
///
///    - returns： Resolution
public func getResolution() -> String {
    return String("\(SCREEN_WIDTH)*\(SCREEN_HEIGHT)")

}
///  获取idfa
///
///    - returns： idfa
public func getIdfa() -> String {
    return ""
}

///  获取appkey
///
///    - returns： appkey
public func getAppKey() -> String {
    return "bf3b47757f87417fabc7c84ba261b355"
}
/// 获取APPID
///
/// - Returns: APPID
public func getAppId() -> String {
    return "1304314049"
}
///   字典转base64
///
///     - Returns: base64之后的字符串
public func base64DicToString(_ dic:[String:Any]) -> String {
    let dicData:Data = try! JSONSerialization.data(withJSONObject:dic,options: JSONSerialization.WritingOptions.prettyPrinted)
    let dicBase64:String = dicData.base64EncodedString()
    return dicBase64
}

